import 'package:easy_video/controller/app_controller.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'package:easy_video/internal/api/video_api.dart';
import 'package:easy_video/model/video_channel_model.dart';
import 'package:easy_video/model/video_chapter_model.dart';
import 'package:easy_video/model/video_model.dart';

class DetailController extends GetxController {
  late VideoPlayerController playerController;

  List<VideoChannelModel> channel_list = [];

  List<VideoChapterModel> chapter_list = [];

  int channel_current_index = 0;

  late int videoId;

  late VideoModel video;

  bool loading = true;

  bool pick_chapter = false;

  late int current_chapter_id;

  @override
  void onInit() async {
    this.videoId = int.parse(Get.parameters["video_id"]!);
    super.onInit();
    this.resetGet();
  }

  @override
  void onClose() {
    super.onClose();
    this.record();
    try {
      if (this.pick_chapter) {
        this.playerController.dispose();
      }
    } catch (e) {}
  }

  resetGet() async {
    this.getVideoDetail();
    await this.getVideoChannel();
    await this.getChapterList();
    if (this.chapter_list.length > 0) {
      this.playVideo(this.chapter_list.first.Id);
    }
  }

  getVideoDetail() async {
    var response = await VideoApi().detail(this.videoId);
    this.video = VideoModel.fromJson(response.data["data"]);
    this.loading = false;
    this.update();
  }

  getVideoChannel() async {
    var response = await VideoApi().videoChannel(this.videoId);
    for (var item in response.data["data"]) {
      this.channel_list.add(VideoChannelModel.fromJson(item));
    }
    this.update();
  }

  getChapterList() async {
    VideoChannelModel currentChannel =
        this.channel_list[this.channel_current_index];
    var response = await VideoApi()
        .videoChapter(currentChannel.VideoId, currentChannel.Id);
    for (var item in response.data["data"]) {
      this.chapter_list.add(VideoChapterModel.fromJson(item));
    }
    this.update();
  }

  Future<void> playVideo(int chapterId) async {
    this.current_chapter_id = chapterId;
    try {
      if (this.pick_chapter) {
        this.playerController.dispose();
      }
    } catch (e) {}
    //开始获取视频播放链接
    var response = await VideoApi().videoPlayUrl(chapterId);
    print({"播放连接:", response.data["data"]["url"]});
    this.playerController = VideoPlayerController.networkUrl(Uri.parse(
      response.data["data"]["url"],
    ))
      ..initialize().then(
        (value) async {
          //从第几秒播放
          int second = 0;
          //如果用户登录了
          if (AppController().isLogin) {
            //获取播放进度
            var response = await VideoApi().getRecord(this.current_chapter_id);
            if (response.data["data"]?["ok"]) {
              second = response.data["data"]?["second"] ?? 0;
            }
          }
          this.playerController.seekTo(Duration(seconds: second));
        },
      );
    this.pick_chapter = true;
    this.update();
  }

  changeChannel(int index) async {
    this.channel_current_index = index;
    this.chapter_list.clear();
    this.getChapterList();
  }

  record() {
    if (AppController().isLogin && this.pick_chapter) {
      //用户登录了,记录状态
      var second = this.playerController.value.position.inSeconds;
      if (second > 0) {
        VideoApi().record(this.current_chapter_id, second);
      }
    }
  }

  void pauseOrPlay() {
    if (!this.playerController.value.isPlaying) {
      this.playerController.play();
    } else {
      this.playerController.pause();
    }
    this.update();
  }
}
